package table;

import java.awt.*;
import java.awt.event.*;
import java.util.regex.*;
import javax.swing.*;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;

import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class SwingTest1 extends JFrame implements ActionListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	JTextArea text = new JTextArea(5, 29);
	JTextField pattern = new JTextField(35);
	JButton search = new JButton("Search");
	JButton newSearch = new JButton("New Search");
	JTextArea result = new JTextArea(5, 29);
	JTextArea status = new JTextArea(5, 29);
	JTable outputTable = null;

	private boolean DEBUG = false;

	public SwingTest1() {

		super("Swing Test");

		setSize(1000, 1000);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Container container = getContentPane();
		GridLayout grid = new GridLayout(4, 1);
		container.setLayout(grid);

		// set up the top row
		JLabel textLabel = new JLabel("Text: ");
		JPanel row1 = new JPanel();
		row1.add(textLabel);
		JScrollPane scroll = new JScrollPane(text, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
				ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		row1.add(scroll);

		// set up the middle1 row
		JPanel row2 = new JPanel();
		JLabel patternLabel = new JLabel("Pattern: ");
		row2.add(patternLabel);
		row2.add(pattern);
		search.addActionListener(this);
		newSearch.addActionListener(this);
		row2.add(search);
		row2.add(newSearch);

		// set up the bottom row
		JPanel row3 = new JPanel();
		JLabel resultLabel = new JLabel("Result: ");
		result.setEditable(false);
		JScrollPane scroll2 = new JScrollPane(result, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
				ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		row3.add(resultLabel);
		row3.add(scroll2);

		JPanel row4 = new JPanel();
		JLabel textLabel2 = new JLabel("Status: ");
		row4.add(textLabel2);
		status.setEditable(false);
		JScrollPane scroll3 = new JScrollPane(status, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
				ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		row4.add(scroll3);


		//outputTable = new JTable(data, columnNames);
		outputTable = new JTable(new MyTableModel());
		JScrollPane scrollPane = new JScrollPane(outputTable);
		
		outputTable.setAutoCreateRowSorter(true);
		outputTable.setFillsViewportHeight(true);
		outputTable.setDefaultRenderer(Color.class, new ColorRenderer(true));;
		outputTable.setPreferredScrollableViewportSize(new Dimension(500, 70));
        
		
		//Set up tool tips for the sport cells.
		DefaultTableCellRenderer renderer =
		        new DefaultTableCellRenderer();
		renderer.setToolTipText("Click for combo box");
		//sportColumn.setCellRenderer(renderer);
		
		MyTableModel model = (MyTableModel)outputTable.getModel();
		TableColumn column = null;
		for (int i = 0; i < model.getColumnCount(); i++) {
		    column = outputTable.getColumnModel().getColumn(i);
		    if (i == 2) {
		        column.setPreferredWidth(100); //third column is bigger
		    } else {
		        column.setPreferredWidth(50);
		    }
		}
		
		
		
        //Set up column sizes.
       //initColumnSizes(outputTable);
		
		
	       
		// set up the content pane
		container.add(row1);
		container.add(row2);
		container.add(row3);
		container.add(row4);
		container.add(scrollPane);
		
		setContentPane(container);
		setVisible(true);

		
		if (DEBUG) {
			outputTable.addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent e) {
					printDebugData(outputTable);
				}
			});
		}
	}

	@Override
	public void actionPerformed(ActionEvent evt) {
		Object source = evt.getSource();
		if (source == search) {
			checkPattern();
		} else {
			pattern.setText("");
			result.setText("");
		}
	}

	private void checkPattern() {
		try {
			if (Pattern.matches(pattern.getText(), text.getText()))
				result.setText("That pattern was found");
			else
				result.setText("That pattern was not found");
		} catch (PatternSyntaxException pse) {
			result.setText("Regex error: " + pse.getMessage());
		}
	}
	
    /*
     * This method picks good column sizes.
     * If all column heads are wider than the column's cells'
     * contents, then you can just use column.sizeWidthToFit().
     */
    private void initColumnSizes(JTable table) {
        MyTableModel model = (MyTableModel)table.getModel();
        TableColumn column = null;
        Component comp = null;
        int headerWidth = 0;
        int cellWidth = 0;
        Object[] longValues = model.longValues;
        TableCellRenderer headerRenderer =
            table.getTableHeader().getDefaultRenderer();

        for (int i = 0; i < model.getColumnCount(); i++) {
            column = table.getColumnModel().getColumn(i);

            comp = headerRenderer.getTableCellRendererComponent(
                                 null, column.getHeaderValue(),
                                 false, false, 0, 0);
            headerWidth = comp.getPreferredSize().width;

            comp = table.getDefaultRenderer(model.getColumnClass(i)).
                             getTableCellRendererComponent(
                                 table, longValues[i],
                                 false, false, 0, i);
            cellWidth = comp.getPreferredSize().width;

            if (DEBUG) {
                System.out.println("Initializing width of column "
                                   + i + ". "
                                   + "headerWidth = " + headerWidth
                                   + "; cellWidth = " + cellWidth);
            }

            column.setPreferredWidth(Math.max(headerWidth, cellWidth));
        }
    }

	/**
	 * Create the GUI and show it. For thread safety, this method should be
	 * invoked from the event-dispatching thread.
	 */
	private static void createAndShowGUI() {
		// Create and set up the window.
		JFrame frame = new JFrame("SimpleTableDemo");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		// Create and set up the content pane.
		SwingTest1 newContentPane = new SwingTest1();
		// newContentPane.setOpaque(true); //content panes must be opaque
		frame.setContentPane(newContentPane);

		// Display the window.
		frame.pack();
		frame.setVisible(true);
	}

	private void printDebugData(JTable table) {
		int numRows = table.getRowCount();
		int numCols = table.getColumnCount();
		javax.swing.table.TableModel model = table.getModel();

		System.out.println("Value of data: ");
		for (int i = 0; i < numRows; i++) {
			System.out.print("    row " + i + ":");
			for (int j = 0; j < numCols; j++) {
				System.out.print("  " + model.getValueAt(i, j));
			}
			System.out.println();
		}
		System.out.println("--------------------------");
	}

	public static void main(String[] args) {
		// Schedule a job for the event-dispatching thread:
		// creating and showing this application's GUI.
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				createAndShowGUI();
			}
		});
	}
}